#include "threadPool.h"

int makeWorker(threadPool_t *pthreadPool){
    for(int i = 0; i < pthreadPool->threadNum ; i++){
        pthread_create(pthreadPool->tidArr + i, NULL, threadFunc, pthreadPool);
    }   
}

void * threadFunc(void *pargs){
    threadPool_t * pthreadPool = (threadPool_t *) pargs;
    while(1){
        //接受任务
        pthread_mutex_lock(&pthreadPool->taskQueue.mutex);
        if (1 == pthreadPool->isexit){
            printf("I am going to exit!\n");
            pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);
            pthread_exit(NULL);
        }
        while(pthreadPool->taskQueue.queueSize == 0){
            pthread_cond_wait(&pthreadPool->taskQueue.cond, &pthreadPool->taskQueue.mutex);
            if(1 == pthreadPool->isexit){
                printf("I am going to exit!\n");
                pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);
                pthread_exit(NULL);
            }
        }
        printf("child thread got task!\n");
        int netfd = pthreadPool->taskQueue.pFront->netfd;
        cmd_t Cmd = pthreadPool->taskQueue.pFront->command;
        taskDeQueue(&pthreadPool->taskQueue);
        pthread_mutex_unlock(&pthreadPool->taskQueue.mutex);
        //执行任务
        switch(Cmd.token){
            case CMD_CD: cmd_cd(netfd,Cmd); break;
            case CMD_LS: cmd_ls(netfd,Cmd); break;
            case CMD_PUTS: cmd_puts(netfd,Cmd); break;
            case CMD_GETS: cmd_gets(netfd,Cmd); break;
            case CMD_REMOVE: cmd_remove(netfd,Cmd); break;
            case CMD_PWD: cmd_pwd(netfd,Cmd); break;
            case CMD_MKDIR: cmd_mkdir(netfd,Cmd); break;
            case CMD_LOGIN: user_login(netfd,Cmd); break;
            case CMD_SIGNUP: user_signup(netfd,Cmd); break;
            default:
                printf("ERROR COMMAND !\n");
        }
        //恢复空闲
        printf("child thread finished task!\n");
    }
}